Smallest Rectangle Enclosing Black Pixels

An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. The black pixels are connected, i.e., there is only one black region. Pixels are connected horizontally and vertically. Given the location (x, y) of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels.

For example, given the following image:

  1. [
  2. "0010",
  3. "0110",
  4. "0100"
  5. ]

and x = 0, y = 2,
Return 6.

Solution:

  1. public class Solution {
  2. public int minArea(char[][] image, int x, int y) {
  3. int n = image.length, m = image[0].length;
  4. int x1 = x, y1 = y, x2 = x, y2 = y;
  5. int[] dx = {0, 0, -1, 1};
  6. int[] dy = {-1, 1, 0, 0};
  7. Queue<int[]> queue = new LinkedList<>();
  8. Set<Integer> visited = new HashSet<>();
  9. queue.add(new int[]{x, y});
  10. visited.add(x * m + y);
  11. while (!queue.isEmpty()) {
  12. int[] p = queue.poll();
  13. x = p[0]; y = p[1];
  14. if (x < x1) x1 = x;
  15. if (x > x2) x2 = x;
  16. if (y < y1) y1 = y;
  17. if (y > y2) y2 = y;
  18. for (int i = 0; i < 4; i++) {
  19. int nx = x + dx[i], ny = y + dy[i];
  20. if (nx < 0 || nx >= n || ny < 0 || ny >= m || image[nx][ny] != '1') {
  21. continue;
  22. }
  23. if (!visited.contains(nx * m + ny)) {
  24. queue.add(new int[]{nx, ny});
  25. visited.add(nx * m + ny);
  26. }
  27. }
  28. }
  29. return (x2 - x1 + 1) * (y2 - y1 + 1);
  30. }
  31. }